package com.example.com.daervideo.vm;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.example.com.daervideo.activitys.loginRegist.ForgetAndResetPassword;
import com.example.com.daervideo.activitys.loginRegist.LoginActivity;
import com.example.com.daervideo.databinding.ActivityResetBinding;

import com.example.com.daervideo.entity.BaseListEntity;
import com.example.com.daervideo.initerface.ApiService;
import com.example.com.daervideo.utils.DESUtils;
import com.example.com.daervideo.utils.MD5Utils;
import com.example.com.daervideo.utils.RetrofitClient;

import java.lang.ref.WeakReference;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.AppManager;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.http.BaseResponse;
import me.goldze.mvvmhabit.http.ResponseThrowable;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

/**
 * Created by i7-1 on 2018/12/6.
 */

public class ResetViewModel extends BaseViewModel {


    private final ApiService apiService;
    private ActivityResetBinding binding;
    private int time = 60;
    private Handler handler;

    public ResetViewModel(ForgetAndResetPassword context) {
        super(context);
        binding = context.getBinding();
        handler = new MainHandler(context);
        apiService = RetrofitClient.getInstance().create(ApiService.class);
    }

    public BindingCommand getCode = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            String phone = binding.phone.getText().toString().trim();
            if (StringUtils.isEmpty(phone) && phone.length() != 11) {
                ToastUtils.showShort("手机号码有误");
                return;
            }

            binding.buttonCode.setClickable(false);

            apiService.sendResetCode(phone)
                    .compose(RxUtils.bindToLifecycle(context)) //请求与View周期同步
                    .compose(RxUtils.schedulersTransformer()) //线程调度
                    .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Exception {
                            showDialog();
                        }
                    })
                    .subscribe(new Consumer<BaseResponse<BaseListEntity>>() {
                        @Override
                        public void accept(BaseResponse<BaseListEntity> response) throws Exception {
                            dismissDialog();
                            ToastUtils.showShort(response.getMsg());
                            if (response.getCode() == 0) {
                                Message message = handler.obtainMessage(1);     // Message
                                handler.sendMessageDelayed(message, 1000);
                            } else {

                                binding.buttonCode.setClickable(true);
                            }

                        }
                    }, new Consumer<ResponseThrowable>() {
                        @Override
                        public void accept(ResponseThrowable throwable) throws Exception {
                            dismissDialog();
                            ToastUtils.showShort(throwable.message);
                            throwable.printStackTrace();

                            binding.buttonCode.setClickable(true);
                        }
                    });
        }
    });

    public BindingCommand reset = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            String phone = binding.phone.getText().toString().trim();
            String code = binding.code.getText().toString().trim();
            String firstPws = binding.inputPassword.passwordEditText.getText().toString().trim();
            String lastpws = binding.performPassword.passwordEditText.getText().toString().trim();
            if (StringUtils.isEmpty(phone) || phone.length() != 11 || StringUtils.isEmpty(code) || StringUtils.isEmpty(firstPws)) {
                ToastUtils.showShort("填写有误！");
                return;
            }
            if (!firstPws.equals(lastpws)) {
                ToastUtils.showShort("密码不一致！");
            }

            String password = DESUtils.utilEncode(firstPws);

            apiService.resetPws(phone, code, password)
                    .compose(RxUtils.bindToLifecycle(context)) //请求与View周期同步
                    .compose(RxUtils.schedulersTransformer()) //线程调度
                    .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Exception {
                            showDialog();
                        }
                    })
                    .subscribe(new Consumer<BaseResponse<BaseListEntity>>() {
                        @Override
                        public void accept(BaseResponse<BaseListEntity> response) throws Exception {
                            dismissDialog();
                            ToastUtils.showShort(response.getMsg());
                            if (response.getCode() == 0) {
                                //AppManager.getAppManager().finishActivity();
                                Class<LoginActivity> clazz = LoginActivity.class;
                                SPUtils.getInstance().put("isFirst", true);
                                startActivity(clazz);
                                AppManager.getAppManager().finishOtherActivityDelay(clazz);

                            } else {
                                binding.buttonCode.setClickable(true);
                            }

                        }
                    }, new Consumer<ResponseThrowable>() {
                        @Override
                        public void accept(ResponseThrowable throwable) throws Exception {
                            dismissDialog();
                            ToastUtils.showShort(throwable.message);
                            throwable.printStackTrace();

                            binding.buttonCode.setClickable(true);
                        }
                    });
        }
    });

    private class MainHandler extends Handler {
        private final WeakReference<Context> reference;

        public MainHandler(Context activity) {
            reference = new WeakReference<Context>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            Context activity = reference.get();
            if (activity != null) {
                time--;
                binding.buttonCode.setText(time + "s");
                if (time > 0) {
                    Message message = handler.obtainMessage(1);
                    handler.sendMessageDelayed(message, 1000);      // send message
                } else {

                    binding.buttonCode.setClickable(true);
                    binding.buttonCode.setText("获取验证码");
                    time = 60;
                }
            }
            super.handleMessage(msg);
        }
    }

    @Override
    public void onDestroy() {
        handler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }
}
